import axios from 'axios'
import token from './token'
import store from '../store'
import messages from './messages'

// 拦截request,设置全局请求为ajax请求
axios.interceptors.request.use((config) => {
  config.headers['X-Requested-With'] = 'XMLHttpRequest'
  config.headers['Authorization-Token'] = token.get()
  if (config.method === 'get') { // IE 11 cache
    let url = config.url || ''
    if (url.indexOf('?') < 0) {
      url = url + '?_=' + new Date().getTime()
    } else {
      url = url + '&_=' + new Date().getTime()
    }
    config.url = url
  }

  return config
})

axios.interceptors.response.use(
  response => {
    // 该项目后端所有响应状态码均为200
    const resp = response.data
    const code = resp.err_code
    const data = {
      code: code,
      message: messages.get(code) || resp.err_msg,
      data: resp.data
    }
    if (code !== 0) {
      // 认证特别处理
      if (code === 1001) {
        store.dispatch('logout').then(r => token.remove())
      }
      return Promise.reject(data)
    }
    return data
  },
  error => {
    const resp = error.response
    // 认证特别处理
    if (resp.status === 401) {
      store.dispatch('logout').then(r => token.remove())
    }
    return Promise.reject(error.response.data || { code: 1, message: '服务器繁忙，请稍后再试！' })
  }
)

// axios.install = (Vue) => {
//   Vue.prototype.$request = axios
// }

export default axios
